const db = require('../../db');

function deepCopy(p, c) {　　　　
    var c = c || {};　　　　
    for (var i in p) {　　　　　　
        if (typeof p[i] === 'object') {　　　　　　　　
            c[i] = (p[i].constructor === Array) ? [] : {};　　　　　　　　
            deepCopy(p[i], c[i]);　　　　　　
        } else {　　　　　　　　　
            c[i] = p[i];　　　　　　
        }　　　　
    }　　　　
    return c;　　
}

let editWeekReport = {
    config: {
        description: '周报修改',
        cors: {
            origin: ['*'],
            additionalHeaders: ['cache-control', 'x-requested-with']
        }
    },
    method: 'post',
    path: '/report/edit',
    handler: async (request, h) => {
        console.log('编辑接口')

        let request_body = request.payload

        let stateCode;
        let stateMessage;

        let year = request_body.year
        let week = request_body.week

        let result = {
            data: undefined,
            stateCode: '',
            stateMessage: ''
        }
        let promise = function () {
            return new Promise((resolve, reject) => {
                let newData;
                db.report.findOne({
                    year: year,
                    week: week
                }, (err, docs) => {
                    if (err) {
                        reject(err)
                    }
                    let srcData
                    console.log('查询结果', docs)
                    docs.content.children.forEach((item, index) => {
                        if (item.title === request_body.checkedType) {
                            console.log('编辑类型', item.title)
                            srcData = deepCopy(docs)
                            delete srcData._id
                            console.log('index', request_body.index * 1 - 1)
                            console.log('数据', docs.content.children[index].children)
                            docs.content.children[index].children.splice(request_body.index * 1, 1, request_body.content.data)
                        }
                    })
                    db.report.update(srcData, {
                        $set: docs
                    })
                    db.report.findOne({
                        year: year,
                        week: week
                    }, (err, docs) => {
                        resolve(docs)
                    })
                })
            })
        }
        return await promise()
    }
}

module.exports = editWeekReport